package sanrenxing.kechenglx.servlet;

import com.google.gson.Gson;
import sanrenxing.kechenglx.dao.CourseSubjectDao;
import sanrenxing.kechenglx.dao.Impl.CourseSubjectDaoImpl;
import sanrenxing.kechenglx.domian.Course;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @date 2020/10/20 11:01
 * 编辑者：邓志强
 * 功能：
 */
@WebServlet("/FindCourse")
public class FindCourse extends HttpServlet {
    //创建数据层操作对象
    CourseSubjectDao csd=new CourseSubjectDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求字符集
        req.setCharacterEncoding("utf-8");
        //设置响应字符集和内容类型
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        //接收来自客户端的请求方法
        String method=req.getParameter("method");
        if (method.equals("findCourse")){
            //查询课程名称
            this.findCourse(req,resp);
        }else if (method.equals("selectCourse")){
            //选择课程
            this.selectCourse(req,resp);
        }
    }

    /**
     * 选择课程
     * @param req
     * @param resp
     */
    private void selectCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //创建输出流
        PrintWriter out=resp.getWriter();

    }

    /**
     * 查询课程名称
     * @param req
     * @param resp
     */
    private void findCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //创建输出流对象
        PrintWriter out=resp.getWriter();
        //调用数据层方法获取课程集合
        List<Course> courseList=csd.findCourse();
        //调用数据层方法获得数据的总行数
        int totalRows=csd.count();
        //定义映射集合对象
        Map<String,Object> mapData=new HashMap<String,Object>();
        //在映射集合中添加key为code，值为0的状态码
        mapData.put("code",0);
        //在映射集合中添加key为msg,值为响应信息“ ”字符串
        mapData.put("msg","");
        //在映射集合中添加key为count,值总行数totalRows
        mapData.put("count",totalRows);
        //在映射集合中添加key为data,值为courseList集合对象
        mapData.put("data",courseList);
        //建立Gson对象
        Gson gson=new Gson();
        //使用Gson对象把映射集合转换为json格式数据
        String json1=gson.toJson(mapData);
        //将json数据输出到客户端
        out.write(json1);
        //关闭输出流对象
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
